package com.rfsp.common.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.rfsp.common.config.PropertyConfig;

//@Component
public class XssFilter implements Filter {

	public Logger log = LoggerFactory.getLogger(XssFilter.class);
	
	@Autowired
	PropertyConfig config;
	
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("XssFilter 初始化！！！");
	}

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
    	HttpServletRequest  res = (HttpServletRequest)  request;
		HttpServletResponse rsp = (HttpServletResponse) response;

    	try {
			
	    	String uri   = WebUtils.getPathWithinApplication(WebUtils.toHttp(request));
	    	String unXss = config.getUnxss_url();
	    	boolean bFlag = false; //是否url包含
	    	if(uri.contains(".")) {
	    		bFlag = true;
			}
	    	
	    	if(StringUtils.isNotBlank(unXss)){
	    		List<String> urlList = Arrays.asList(unXss.split(";"));
	    		if(urlList.contains(uri)) {
	    			bFlag = true;
	    		}
	    	}
	    	
	    	if (bFlag){
	    		chain.doFilter(request, response);
	    	} else {
	    		String enctype = request.getContentType();
	    		if(enctype!=null && enctype.contains("multipart/form-data") ){
	    			CommonsMultipartResolver resolver = new CommonsMultipartResolver(res.getSession().getServletContext());
	    			resolver.setDefaultEncoding("UTF-8");
	    			MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(res);
	    			multipartRequest.setAttribute("fileList", multipartRequest.getFiles("file"));
	    			chain.doFilter(new XssWrapper(multipartRequest), response);
	    			
	    		}else{
	    			chain.doFilter(new XssWrapper(res), response);
	    		}
	    	}
    	}catch (Exception e) {
    		chain.doFilter(request, response);
//			e.printStackTrace();
		}
	}
}
